﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using IceTea.Domain.Models;
using IceTea.Domain;
using System.Security;

namespace IceTea.Controllers
{
    public class AccountController : BaseController
    {        
        [AllowAnonymous]
        //[RequireHttps]
        public ActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        //[RequireHttps]
        public ActionResult Login(IceTeaMembership member, string ReturnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View("Login", member);
            }

            //Set the auth cookie
            FormsAuthentication.SetAuthCookie(member.UserName, false);

            //Clear the session of UserRoleProfile
            ClearRoleProfile(HttpContext);


            if (!string.IsNullOrEmpty(ReturnUrl) && Url.IsLocalUrl(ReturnUrl)
                && ReturnUrl.StartsWith("/") && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
            {
                return Redirect(ReturnUrl);
            }
            
            return RedirectToAction("Index", "Home");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(User newuser)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Result = "SignUpFail";
                return View(newuser);
            }

            if (IceTea.Domain.Models.User.CreateNewUser(newuser))
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Unexpected exception occurred while creating new user, please try again");
                return View(newuser);
            }
        }

        [AllowAnonymous]
        public ActionResult UserInfo()
        {
            User user = null;
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                user = IceTea.Domain.Models.User.RetrieveUser(HttpContext.User.Identity.Name);
            }
            return View(user);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            ClearRoleProfile(HttpContext);
            return RedirectToAction("Index", "Home");
        }
    }
}
